<template>
  <div class="login-modal w-[430px]">
    <BasicModal :title="`账户${state.loginTitle}`" @confirm="submitLogin" @register="loginModalRegister" to=".login-modal">
      <n-card :bordered="false" size="large" class="login-card s:px-0">
        <div class="flex items-center justify-between">
          <div class="form-content rounded-lg pl-0 my-0 mx-auto">
            <h1 class="text-center text-2xl font-semibold mb-6">ChatGPT</h1>
            <n-form :model="state.loginForm" :show-label="false" :rules="state.loginTitle === '注册' ? formRules : {}"
              @keyup.enter="submitLogin(state.loginForm)" ref="loginFormRef">
              <n-form-item path="username">
                <n-input v-model:value="state.loginForm.username" :allow-input="noSideSpace" clearable :minlength="3"
                  :maxlength="12" :disabled="state.loginLoading" placeholder="用户名" size="large" type="text"
                  class="dark:bg-[#303033]">
                  <template #prefix>
                    <n-icon :component="Person" />
                  </template>
                </n-input>
              </n-form-item>
              <n-form-item path="password" v-if="state.loginTitle === '登录'">
                <n-input v-model:value="state.loginForm.password" :disabled="state.loginLoading" placeholder="密码"
                  :allow-input="noSideSpace" show-forget-on="mousedown" show-password-on="click" size="large" clearable
                  type="password" class="dark:bg-[#303033]" :minlength="6" :maxlength="18">
                  <template #prefix>
                    <n-icon :component="LockClosed" />
                  </template>
                </n-input>
              </n-form-item>
              <n-form-item path="password" v-else>
                <n-input v-model:value="state.loginForm.password" :disabled="state.loginLoading" placeholder="密码"
                  :allow-input="noSideSpace" size="large" clearable type="text" class="dark:bg-[#303033]" :minlength="6"
                  :maxlength="18">
                  <template #prefix>
                    <n-icon :component="LockClosed" />
                  </template>
                </n-input>
              </n-form-item>
            </n-form>
            <n-checkbox v-model:checked="state.rememberPwd" v-show="state.loginTitle === '登录'" class="mb-2">
              记住密码
            </n-checkbox>
          </div>
        </div>
      </n-card>
      <template #action>
        <div class="w-full flex flex-col">
          <n-button :loading="state.loginLoading" class="w-full h-10" type="primary"
            @click="state.loginTitle === '登录' ? submitLogin(state.loginForm) : submitRegister()">
            {{ state.loginTitle }}
          </n-button>
          <div class="flex justify-center align-center mt-4">
            <n-button color="#777777" text @click="switchFn">
              {{ state.loginTitle === '登录' ? '创建账户' : '返回登录' }}
            </n-button>
          </div>
        </div>
      </template>
    </BasicModal>
  </div>
</template>

<script setup>
import { reactive, getCurrentInstance, defineAsyncComponent } from 'vue'
import { useUserStore } from '@/store'
import { login, register } from '@api/userApi'
import { noSideSpace } from '@/utils'
import { Person, LockClosed } from '@vicons/ionicons5'
import { useModal } from '@c/Modal/useModal'

const BasicModal = defineAsyncComponent(() => import('@c/Modal/BasicModal.vue'))
const { proxy } = getCurrentInstance()
const userStore = useUserStore()

const emit = defineEmits(['getMsgList', 'register'])

const state = reactive({
  rememberPwd: false,
  loginTitle: '登录',
  loginLoading: false,
  loginForm: {
    username: '',
    password: '',
  }
})

const formRules = {
  username: {
    required: true,
    validator(rule, value) {
      if (!value) return new Error('请输入用户名')
      if (value.length < 3 || value.length > 12) return new Error('用户名必须在3至12位')
      return true
    },
    trigger: 'input',
  },
  password: {
    required: true,
    validator(rule, value) {
      if (!value) return new Error('请输入密码')
      if (value.length < 6 || value.length > 18) return new Error('密码长度必须在6至18位')
      return true
    },
    trigger: 'input',
  },
}

const [loginModalRegister, {
  openModal: basicOpenLoginModal,
  closeModal: closeLoginModal,
}] = useModal(state.loginForm)

const openLogin = () => {
  state.loginTitle = '登录'
  setLoginForm()
  basicOpenLoginModal()
}

const switchFn = () => {
  proxy.$refs.loginFormRef.restoreValidation()
  if (state.loginTitle === '登录') {
    state.loginTitle = '注册'
    state.loginForm = {
      username: '',
      password: '',
    }
  } else {
    state.loginTitle = '登录'
    setLoginForm()
  }
}

const setLoginForm = () => {
  const user = localStorage.getItem('user')
  if (user?.trim()) {
    state.rememberPwd = true
    const { username, password } = JSON.parse(user)
    if (username && password) {
      state.loginForm = {
        username: username.trim(),
        password: password.trim(),
      }
    }
  }
}

const submitLogin = async (formData) => {
  if (state.loginTitle === '登录') {
    if (formData.username === '' || formData.password === '') return $message.error('用户名或密码不能为空！')
  }
  state.loginLoading = true
  let loginMsgLoading = $message.loading(`正在${state.loginTitle}中...`, { duration: 0 })
  try {
    const res = await login(formData)
    if (res?.statusCode === 200) {
      localStorage.setItem('user', state.rememberPwd ? JSON.stringify(formData) : '')
      $message.destroyAll()
      $message.success(res.message, { duration: 1500 })
      userStore.setUserState(res.data)
      state.isNewChat = true
      emit('getMsgList')
      closeLoginModal()
    }
  } finally {
    loginMsgLoading && loginMsgLoading.destroy()
    loginMsgLoading = null
    state.loginLoading = false
  }
}

const submitRegister = () => {
  proxy.$refs.loginFormRef.validate(async validate => {
    if (validate) return false
    state.loginLoading = true
    let registerMsgLoading = $message.loading(`正在${state.loginTitle}中...`, { duration: 0 })
    try {
      const res = await register(state.loginForm)
      if (res?.statusCode === 200) {
        $message.destroyAll()
        closeLoginModal()
        $message.loading('注册成功,正在为你自动登录...', { duration: 0 })
        state.rememberPwd = true
        setTimeout(() => {
          submitLogin(state.loginForm)
        }, 1000)
      }
    } finally {
      registerMsgLoading && registerMsgLoading.destroy()
      registerMsgLoading = null
      state.loginLoading = false
    }
  })
}

defineExpose({
  openLogin
})
</script>

<style lang="less" scoped>
.login-modal {
  &:deep(.n-dialog__content) {
    margin-top: 12px;

    .login-card {
      border-radius: 6px;
      max-width: 400px;

      .n-card__content {
        padding: 0;

        .form-content {
          width: 100%;

          .n-form {
            width: 100%;

            .n-input {
              height: 40px;
              display: flex;
              align-items: center;
              background-color: #e8f0fe;
              border: none;

              &:focus:not(:focus-visible) {
                border: none;
              }

              .n-input__prefix {
                margin-right: 10px;
              }

              .n-input__border {
                border-color: #f5f5f5;
              }
            }
          }
        }
      }
    }
  }
}
</style>